<template>
  <node-view-wrapper>
    <div class="flex flex-col bg-gray-100 p-2 lg:p-4 rounded-md">
      <div v-if="response" class="w-full mt-1">
        <span id="response"
          class="inline-block w-full max-w-full max-h-80 bg-white p-2 border border-slate-300/20 rounded-md prose dark:prose-invert tiptap overflow-y-auto"
          v-html="response"></span>
      </div>
      <!-- <label class="mt-1" for="prompt">
        <div class="text-gray-600 mb-2 px-1 flex items-center text-sm">
          <span class="mr-2">Prompt</span>
        </div>
        <textarea id="prompt" name="prompt"
          class="px-2 rounded-md w-full border border-slate-300/20 focus:outline-none focus:ring-none" rows="2"
          v-model="prompt"></textarea>
      </label> -->
      <label class="mt-1" for="question">
        <!-- <div class="text-gray-600 mb-2 px-1 text-sm">Question</div> -->
        <textarea id="question" name="question"
          class="px-2 rounded-md w-full border border-slate-300/20 font-medium focus:outline-none focus:ring-none"
          rows="3" v-model="question"></textarea>
      </label>
      <div class="flex flex-row">
        <div>
          <button v-if="response" class="bg-slate-500 hover:bg-slate-700 text-white px-1 rounded-md mr-2"
            @click.stop="onAdd">
            <RemixIcon class="mr-1" name="add-line"></RemixIcon>
            <span>{{ i18n.t('insert') }}</span>
          </button>
          <button v-if="response" class="bg-slate-500 hover:bg-slate-700 text-white px-1 rounded-md mr-2"
            @click.stop="onCopy">
            <RemixIcon class="mr-1" name="file-copy-2-line"></RemixIcon>
            <span>{{ i18n.t('copy') }}</span>
          </button>
          <button class="bg-slate-500 hover:bg-slate-700 text-white px-1 rounded-md" @click.stop="onDiscard">
            <RemixIcon class="mr-1" name="delete-bin-4-line"></RemixIcon>
            <span>{{ i18n.t('discard') }}</span>
          </button>
        </div>
        <div class="flex-1 flex justify-end">
          <button class="bg-purple-500 hover:bg-purple-700 text-white px-1 rounded-md justify-self-end"
            @click.stop="onGenerate" :disabled="loading">
            <RemixIcon v-if="loading" class="inline-block animate-spin duration-300" name="loader-3-line"></RemixIcon>
            <RemixIcon v-else name="send-plane-line"></RemixIcon>
            <span class="ml-1">{{ i18n.t(loading ? 'loading' : 'generate') }}</span>
          </button>
        </div>
      </div>
    </div>
  </node-view-wrapper>
</template>

<script setup>
import { nodeViewProps, NodeViewWrapper } from '@tiptap/vue-3'
import { ref, nextTick, onMounted, toRaw, computed } from 'vue'
import { marked } from 'marked'
import RemixIcon from '@/components/RemixIcon.vue'
import i18n from '../../i18n/index.ts';
const props = defineProps(nodeViewProps)
const attrs = props?.node?.attrs;
const question = ref(attrs?.question || '')
const prompt = ref(attrs?.prompt || '')
const responseText = ref('')
const response = computed(() => {
  return marked(responseText.value);
})
const loading = ref(false);
// editor变成了响应对象，导致某些方法执行会有问题，所以需要使用toRaw转换一下
const editor = toRaw(props?.editor)
const onGenerate = () => {
  if (!question.value) return;
  let result = '';
  loading.value = true;
  editor?.chat(question.value, prompt.value, (content) => {
    result += content;
    responseText.value = result;
    nextTick(() => {
      const aiChatContent = document.getElementById('response');
      aiChatContent && aiChatContent.scrollTo({ top: aiChatContent.scrollHeight, behavior: 'smooth' });
    })
  }, () => {
    loading.value = false;
  })
}
const onAdd = () => {
  editor?.chain().insertContent(response.value).run();
  onDiscard();
}
const onCopy = () => {
  var clipboardItem = clipboardItem = new ClipboardItem({
    ['text/html']: new Blob([response.value], { type: 'text/html' }),
  })
  navigator.clipboard.write([clipboardItem]).then(() => {
    editor?.message?.success(`${i18n.t(['copy', 'success'])}`);
  }, function () {
    editor?.message?.console.error(`${i18n.t(['copy', 'fail'])}`);;
  }
  )
}
const onDiscard = () => {
  props.deleteNode();
}
onMounted(() => {
  if (question.value) {
    onGenerate();
  }
})
</script>

<style lang="scss"></style>